package com.tanhua.manager.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.domain.db.Admin;
import com.tanhua.manager.api.db.AdminApi;
import com.tanhua.manager.exception.BusinessException;
import com.tanhua.util.JwtUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Reference
    private AdminApi adminApi;

    public LineCaptcha verification(String uuid) {
        // 1、通过hutool生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(300, 100);
        // 2、将验证码随机数存储到reids中
        stringRedisTemplate.opsForValue().set("manager_code_" + uuid, lineCaptcha.getCode(), Duration.ofMinutes(5));
        return lineCaptcha;
    }

    public String login(String username, String password, String verificationCode, String uuid) {

        if (StrUtil.isEmpty(username) || StrUtil.isEmpty(password)) {
            throw new BusinessException("用户名密码为空");
        }

        if (StrUtil.isEmpty(verificationCode) || StrUtil.isEmpty(uuid)) {
            throw new BusinessException("验证码为空");
        }

        String redisCode = stringRedisTemplate.opsForValue().get("manager_code_" + uuid);
        if (StrUtil.isEmpty(redisCode) || !verificationCode.equals(redisCode)) {
            throw new BusinessException("验证码不正确");
        }

        Admin admin = adminApi.login(username);
        if (admin == null) {
            throw new BusinessException("此用户不存在");
        }

        String md5Pwd = SecureUtil.md5(password);
        if (!admin.getPassword().equals(md5Pwd)) {
            throw new BusinessException("密码错误");
        }
        // 清除验证码
        stringRedisTemplate.delete("manager_code_" + uuid);

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", admin.getId());
        claims.put("username", admin.getUsername());
        String token = JwtUtil.createToken(claims);

        String json = JSON.toJSONString(admin);
        stringRedisTemplate.opsForValue().set("manager_token_" + token, json, Duration.ofHours(1));
        return token;
    }

    public Admin findAdminByToken(String token) {
        // 前端工程师，有一个不成文的规定，在拼接token的时候前面会携带一个 Bearer（持有者）
        token = token.replaceAll("Bearer ", "");
        String json = stringRedisTemplate.opsForValue().get("manager_token_" + token);
        if (StrUtil.isEmpty(json)){
            return null;
        }
        Admin admin = JSON.parseObject(json, Admin.class);
        admin.setPassword(null); // 不要给前端返回密码

        stringRedisTemplate.opsForValue().set("manager_token_" + token, json, Duration.ofHours(1)); // 续期 1个小时
        return admin;
    }

    public void logout(String token) {
        // 前端工程师，有一个不成文的规定，在拼接token的时候前面会携带一个 Bearer（持有者）
        token = token.replaceAll("Bearer ", "");
        stringRedisTemplate.delete("manager_token_" + token);
    }
}
